package com.gitee.hermer.engine.jars.app.sdk.eventbus;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.springframework.beans.factory.InitializingBean;

import com.gitee.hermer.boot.jee.commons.bean.utils.BeanLocator;
import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.exception.PaiUException;
import com.gitee.hermer.boot.jee.commons.reflect.ReflectUtils;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;

public class EngineAppEventBusSender implements InitializingBean{

	private Method sendQueueEventBus;
	private Method sendBroadcastEventBus;

	private Object eventBusSender;

	public void sendQueueEngineHandleEvent(String eventName,Serializable... args) throws PaiUException{
		try {
			ReflectUtils.invoke(eventBusSender, new Object[]{eventName,args}, sendQueueEventBus);
		} catch (Throwable e) {
			throw new PaiUException(ErrorCode.SYSTEM_ERROR, e, "发送错误！");
		} 
	}

	public void sendBroadcastEngineHandleEvent(String eventName,Serializable... args) throws PaiUException{
		try {
			ReflectUtils.invoke(eventBusSender, new Object[]{eventName,args}, sendBroadcastEventBus);
		} catch (Throwable e) {
			throw new PaiUException(ErrorCode.SYSTEM_ERROR, e, "发送错误！");
		} 
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(EngineConstant.CLASS_EVENT_BUS_SENDER != null){
			for (Method method : EngineConstant.CLASS_EVENT_BUS_SENDER.getDeclaredMethods()) {
				if(method.getName().equals(EngineConstant.BEAN_METHOD_NAME_SEND_BROADCAST_EVENTBUS)){
					sendBroadcastEventBus = method;
				}else if(method.getName().equals(EngineConstant.BEAN_METHOD_NAME_SEND_QUEUE_EVENTBUS)){
					sendQueueEventBus = method;
				}
			}
			eventBusSender = BeanLocator.getBean(EngineConstant.CLASS_EVENT_BUS_SENDER);
		}
	}

}
